﻿using System;
using Common.Enumerations;
using Common.Service;
using Core.Domain.Model;
using NSBus.Dto.Commands;
using NServiceBus;
using Sanelib.Common.Helpers;
using Sanelib.DataOperation;
using Sanelib.Dto.Enumerations;

namespace NSBus.Server.CommandHandlers
{
    public class RegisterNewMemberHandler : MessageHandler<RegisterNewMemberCommand>
    {
        private readonly ICryptographer _cryptographer;
        private readonly IRepository<Member> _memberRepository;
        private readonly IRepository<Templete> _templeteRepository;

        public IBus Bus { get; set; }

        public RegisterNewMemberHandler(IRepository<Member> memberRepository, IUnitOfWork unitOfWork, ICryptographer cryptographer, IRepository<Templete> templeteRepository)
            : base(unitOfWork)
        {
            _memberRepository = memberRepository;
            _cryptographer = cryptographer;
            _templeteRepository = templeteRepository;
        }

        public override void HandleMessage(RegisterNewMemberCommand message)
        {
            var token = GetToken();
            var messageBody = _templeteRepository.GetByKey(Property.Of<Templete>(x => x.Name), "Member Registration").Value;
            var serverhost = _memberRepository.GetByKey(Property.Of<Member>(x => x.Code), "serverhost");

            Bus.SendLocal<SendEmailCommand>(m =>
            {
                m.To = message.Email;
                m.Subject = "Sanelib Password Recovery Instructions";
                m.MessageBody = string.Format(messageBody, message.Url, token);
            });

            var member = new Member
            {
                Id = GuidComb.New(),
                TagId = string.Empty,
                Code = message.Code,
                Name = message.Name,
                DateOfBirth = message.DateOfBirth,
                Address = message.Address,
                Email = message.Email,
                Mobile = message.Mobile,
                ScreenMessage = string.Empty,
                ValidFrom = DateTime.Now,
                ValidTo = DateTime.Now.AddMonths(1),
                SendSms = true,
                SendEmail = true,
                UsePrint = false,
                Block = false,
                PasswordHash = string.Empty,
                PasswordSalt = string.Empty,
                PasswordRetrievalToken = _cryptographer.ComputeHash(token),
                PasswordRetrievalTokenExpirationDate = SystemTime.Now().AddDays(1),
                FailedAttemptCount = 0,
                Role = Role.Member,
                UserStatus = UserStatus.Active,
                CreatedBy = serverhost.Id,
                CreatedOn = DateTime.Now
            };

            _memberRepository.Add(member);
        }
        private string GetToken()
        {
            return _cryptographer.CreateSalt().Substring(0, 10);
        }
    }
}
